package com.ucode.application.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ucode.application.security.LoginUserInfo;
import com.ucode.springboot.starter.security.entity.UcodeAuthenticatioToken;
import com.ucode.springboot.starter.security.entity.UcodeUser;
import com.ucode.springboot.starter.security.entity.UcodeUserDetails;
import com.ucode.springboot.starter.security.service.UcodeSecurityOperationService;
import com.ucode.sys.model.User;
import com.ucode.sys.service.RoleService;
import com.ucode.sys.service.UserService;
import com.ucode.tool.base.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags="系统登录 ")
@RestController
@Validated
public class LoginController {
    
    @Autowired
    private UcodeSecurityOperationService securityOperationService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    public RoleService roleService; 

    @ApiOperation("密码登录")
    @PostMapping(value = "/pswLogin")
    public ResponseResult<Object> pswLogin(HttpServletRequest request,
            @ApiParam(value="用户名/邮箱/手机号",required=true) @RequestParam(value = "username", required=true) String username,
            @ApiParam(value="密码",required=true) @RequestParam(value = "password", required=true) String password){
        
        UcodeAuthenticatioToken obj = securityOperationService.login(request, username, password);
        UcodeUserDetails details = (UcodeUserDetails) obj.getPrincipal();
        UcodeUser ucodeUser = details.getUser();
        User user = userService.findById(Long.valueOf(ucodeUser.getUserId()));
        LoginUserInfo userInfo = new LoginUserInfo(user, obj.getToken(), ucodeUser.getRoles());
        return ResponseResult.success(userInfo);
    }
    
    @ApiOperation("短信验证码登录")
    @PostMapping(value = "/smsLogin")
    public ResponseResult<Object> smsLogin(HttpServletRequest request,
            @ApiParam(value="手机号",required=true) @RequestParam(value = "mobile", required=true) String mobile,
            @ApiParam(value="短信验证码",required=true) @RequestParam(value = "smsCode", required=true) String smsCode){
        System.err.println(request.getHeader("Authorization"));
        return null;
    }
}
